'use strict'; 
const jwt = require('jsonwebtoken');
const config = require('../config');
async function jwtHandler(ctx, next) {
  // 将 token 中的数据解密后存到 ctx 中
  const ignore = config.jwt.ignore;
  let needVerify = true;
  const { request } = ctx;
  const { originalUrl, headers } = request;
  const path = originalUrl.replace(config.routerPrefix, '');
  for(const regex of ignore) {
    if (new RegExp(regex.replace(/\*/ig, '.*')).test(path)) {
      needVerify = false;
      break;
    }
  }
  if (needVerify) {
    try {
      if (typeof headers.authorization === 'string') {
        const token = headers.authorization;
        ctx.jwtData = jwt.verify(token, config.jwt.secret);        
      } else {
        ctx.throwError('No Authorization', ctx.errorCode.TOKEN);
      }
    } catch (err) {
      ctx.throwError(err.message, ctx.errorCode.TOKEN);
    }
    return await next();
  } else {
    return await next();
  }  
}
module.exports = jwtHandler;